package sort1;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-05-09
 * Time: 6:45
 */
public class sortDeom1 {
    public static void main(String[] args) {
        int[] a = {99,45,34,12,32,35,12,89};
        quickSort(a);
        System.out.println(Arrays.toString(a));
    }

    private static void quickSort(int[] a) {
        quick(a,0,a.length-1);
    }

    private static void quick(int[] a, int start, int end) {
        if (start >= end){
            return;
        }
        if(end - start +1 <= 4){
            inesrtSort(a,start,end);
            return;
        }
        int mid = findmidIndex(a,start,end);
        swap(a,start,mid);
        int poviot = paitition(a,start,end);
        quick(a,start,poviot-1);
        quick(a,poviot+1,end);
    }

    private static int paitition(int[] a, int start, int end) {
        int i = start;
        int poviot = a[i];
        while (start < end){
            while (start < end && a[end] >= poviot){
                end--;
            }
            a[start] = a[end];
            while (start < end && a[start] <= poviot){
                start++;
            }
            a[end] = a[start];
        }
        a[start] = poviot;
        return start;
    }

    private static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

    private static int findmidIndex(int[] a, int start, int end) {
        int mid = (start + end)/2;
        if(a[start] > a[end]){
            if(a[start] < a[mid]){
                return start;
            }else  if(a[end] > a[mid]){
                return end;
            }else {
                return mid;
            }
        }else {
            if(a[start] > a[mid]){
                return start;
            }else if(a[end] < a[mid]){
                return end;
            }else {
                return mid;
            }
        }
    }

    private static void inesrtSort(int[] a, int start, int end) {
        for (int i = start+1; i <= end; i++) {
            int tmp = a[i];
            int j = i -1 ;
            for (; j >= 0 ; j--) {
                if(a[j] > tmp){
                    a[j+1] = a[j];
                }else {
                    break;
                }
            }
            a[j+1] = tmp;
        }
    }
}
